﻿using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using Server.Functions;
using Server.Comm;
using Server.Utils.JSON;
using Server.Login;
using System.Collections;

namespace Server.Account
{
    public sealed class AccountMgr : Singleton<AccountMgr>
    {
        ArrayList m_arrAccount = null;

        public AccountMgr()
        {
            m_arrAccount = new ArrayList();
        }

        public void Init()
        {
            //listen event
            CommMgr.GetInstance().OnConnected += new ConnectedHandler(OnClientConnected);
        }

        private void OnClientConnected(CommObj commObj)
        {
            commObj.OnReceive += new ReceiveHandler(OnClientReceive);
            commObj.BeginReceive();
        }

        private void OnClientReceive(CommObj sender, JSONObject obj)
        {
            sender.OnReceive -= new ReceiveHandler(OnClientReceive);

            ConnectData connectData = new ConnectData();
            connectData.ReadData(obj);

            LoginData lgData = LoginMgr.GetInstance().GetLoginDataByGuid(connectData.Guid);
            if (lgData == null)
            {
                //valid failed
                sender.Close();
            }

            //login valid succeed
            //connected
            AccountConnected(sender, lgData);
        }

        public void AccountConnected(CommObj commObj, LoginData lgData)
        {
            lgData.connected = true;

            AccountObj accountObj = new AccountObj(commObj, lgData.uid, lgData.guid);
            m_arrAccount.Add(accountObj);

            accountObj.Start();
        }
    }
}